package secondriver.qiniucs.client;

import java.util.concurrent.atomic.AtomicInteger;

import secondriver.qiniucs.client.UploadService.LocalBinder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private static String TAG = "MainActivity";

	private ImageView imageView;
	private Button uploadBtn;

	private FileEntity fileEntity = new FileEntity();

	private final AtomicInteger notificationId = new AtomicInteger(0);

	private UploadService uploadService;

	private boolean isChooseFile = false;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPLOAD) {
				fileEntity.setNotificationId(notificationId.getAndIncrement());
				uploadService.upload(fileEntity);
			}
		}
	};

	ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			uploadService = ((LocalBinder) service).getService();
		}
	};

	WifiManager wifiManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.imageView);
		uploadBtn = (Button) findViewById(R.id.uploadBtn);
		uploadBtn.setOnClickListener(this);
		registerForContextMenu(imageView);

		wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

		Log.i(TAG, "wifiManager " + wifiManager.isWifiEnabled());
		Intent sericeIntent = new Intent(UploadService.ACTION_UPLOAD_SERVCE);
		bindService(sericeIntent, conn, BIND_AUTO_CREATE);

		if (!wifiManager.isWifiEnabled()) {
			new AlertDialog.Builder(this)
					.setTitle(R.string.tip)
					.setMessage(R.string.open_wifi)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.setHeaderTitle(R.string.chose_file_msg);
		menu.setHeaderIcon(android.R.drawable.ic_menu_upload);
		menu.add(MENU_GROUP_ID_0, MENU_ITEM_ID_0, Menu.NONE,
				R.string.browse_file_msg);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == MENU_ITEM_ID_0) {
			Intent intent = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			this.startActivityForResult(intent, CHOOSE_IMAGE_CODE);
			return true;
		}
		return super.onContextItemSelected(item);
	}

	/**
	 * 1.检查网络状态 2.选择上传文件 3.填写上传文件信息 4.获取上传Token 5.上传文件
	 */

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.uploadBtn) {
			if (!isChooseFile) {

				Toast toast = Toast.makeText(getBaseContext(),
						R.string.chose_upload_file_msg, Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL, 0, 0);
				toast.show();
				return;
			}
			final View view = LayoutInflater.from(this).inflate(
					R.layout.activity_dialog, null);
			new AlertDialog.Builder(this)
					.setTitle(R.string.settings)
					.setView(view)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									EditText et = (EditText) view
											.findViewById(R.id.key_name);
									String key = et.getText().toString();
									Log.i(TAG,
											String.format(
													"handle upload file filePath=%s key=%s",
													fileEntity.getFilePath(),
													key));
									if (!TextUtils.isEmpty(key)) {
										fileEntity.setKey(key);
										Message m = Message.obtain(handler,
												UPLOAD, null);
										m.sendToTarget();
									} else {
										Toast.makeText(getBaseContext(),
												R.string.info_input_key_msg,
												Toast.LENGTH_LONG).show();
									}
								}
							})
					.setNegativeButton(android.R.string.cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CHOOSE_IMAGE_CODE && resultCode == RESULT_OK
				&& null != data) {
			Uri uri = data.getData();
			Log.i(TAG, "Uri=" + uri);
			Cursor cursor = getContentResolver().query(
					uri,
					new String[] { MediaStore.Images.Media.DATA,
							MediaStore.Images.Media.MIME_TYPE }, null, null,
					null);
			if (cursor.moveToFirst()) {
				String filePath = cursor.getString(cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
				String mimeType = cursor
						.getString(cursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE));
				cursor.close();
				fileEntity.setFilePath(filePath);
				fileEntity.setMimeType(mimeType);
				Bitmap bm = this.getBitmap(filePath);
				imageView.setImageBitmap(bm);
				isChooseFile = true;
			}
		}
	}

	protected void onDestroy() {
		super.onDestroy();
		if (null != uploadService && null != conn) {
			unbindService(conn);
		}
	};

	private Bitmap getBitmap(String pathName) {
		Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);

		int w = options.outWidth;
		int h = options.outHeight;

		int scaleW = w / imageView.getWidth();
		int scaleH = h / imageView.getHeight();

		int scale = scaleW > scaleH ? scaleH : scaleW;
		scale = scale < 1 ? 1 : scale;

		int newW = w / scale;
		int newH = w / scale;

		options.inJustDecodeBounds = false;
		options.outWidth = newW;
		options.outHeight = newH;

		Log.i(TAG, String.format("getBitmap src(%d,%d) new(%d, %d) scale=%d .",
				w, h, newW, newH, scale));
		return BitmapFactory.decodeFile(pathName, options);
	}

	public class FileEntity {
		private String filePath;
		private String key;
		private String mimeType;
		private int notificationId;

		public FileEntity() {
			super();
		}

		public String getFilePath() {
			return filePath;
		}

		public String getKey() {
			return key;
		}

		public String getMimeType() {
			return mimeType;
		}

		public void setFilePath(String filePath) {
			this.filePath = filePath;
		}

		public void setKey(String key) {
			this.key = key;
		}

		public void setMimeType(String mimeType) {
			this.mimeType = mimeType;
		}

		public int getNotificationId() {
			return notificationId;
		}

		public void setNotificationId(int notificationId) {
			this.notificationId = notificationId;
		}

	}

	protected static final int UPLOAD = 0;

	public static final int MENU_GROUP_ID_0 = Menu.FIRST;

	public static final int MENU_GROUP_ID_1 = Menu.FIRST + 1;

	public static final int MENU_ITEM_ID_0 = Menu.FIRST;

	public static final int MENU_ITEM_ID_1 = Menu.FIRST + 1;

	public static final int CHOOSE_IMAGE_CODE = 1;
}
